<?php

namespace App\Services;

use App\Models\Option as OptionMdl;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Exception;

class Config
{
    //public $expires = 86400;

    /**
     * 删除配置缓存
     */
    public static function delCache($key, $alias = '', $adminId = '')
    {
        if ($alias) {
            $cacheKey = 'option--' . $key . '_' . $alias . '_' . $adminId;
        } else {
            $cacheKey = 'cache--' . $key;
        }

        Cache::forget($cacheKey);
    }

    /**
     * 获取文件上传配置
     */
    public static function getUploadSetting()
    {
        $key = 'upload_setting';
        $cacheKey = 'cache--' . $key;
        $uploadSetting = self::getOption($key, $key);
        if (empty($uploadSetting)) {
            $uploadSetting = [
                'storage' => 'local',
                'qiniu' => [
                    'accesskey' => '',
                    'secretkey' => '',
                    'bucket' => '',
                    'url' => ''
                ],
                'tencentyun' => [
                    'secret_id' => '',
                    'secret_key' => '',
                    'region' => '',
                    'bucket' => '',
                    'url' => ''
                ],
                'aliyun' => [
                    'access_key_id' => '',
                    'access_key_secret' => '',
                    'bucket' => '',
                    'endpoint' => '',
                    'bucket_domain' => ''
                ],
                'mimetype' => [
                    'image' => [
                        'max_filesize' => '10240', // 单位KB
                        'extensions' => 'jpg,jpeg,png,gif,bmp4'
                    ],
                    'video' => [
                        'max_filesize' => '10240',
                        'extensions' => 'mp4,avi,wmv,rm,rmvb,mkv'
                    ],
                    'audio' => [
                        'max_filesize' => '10240',
                        'extensions' => 'mp3,wma,wav'
                    ],
                    'file' => [
                        'max_filesize' => '10240',
                        'extensions' => 'txt,pdf,doc,docx,xls,xlsx,ppt,pptx,zip,rar'
                    ]
                ],
            ];
        }

        $config = cache($cacheKey);
        if (!$config) {
            $max_filesizes = [];
            $fileexts = [];
            foreach ($uploadSetting['mimetype'] as $setting) {
                $extensions = explode(',', trim($setting['extensions']));
                if (!empty($extensions)) {
                    $max_filesize = intval($setting['max_filesize']);
                    foreach ($extensions as $ext) {
                        if (!isset($max_filesizes[$ext]) || $max_filesize > $max_filesizes[$ext]) {
                            $max_filesizes[$ext] = $max_filesize;
                            $fileexts[] = $ext;
                        }
                    }
                }
            }

            $config = $uploadSetting;
            $config['max_filesizes'] = $max_filesizes;
            $config['fileexts'] = $fileexts;
            cache([$cacheKey => $config], 3600 * 6);
        }

        return $config;
    }

    /**
     * 设置配置(通用)
     *
     * @param $key 配置名,都小写
     * @param $alias 配置名别称
     * @param $data 配置值
     * @param string $adminId 管理员ID
     * @param string $field 配置值里的键值
     * @param int $expires 过期时间
     */
    public static function setOption($key, $alias, $data, $adminId = '', $field = '', $expires = 86400)
    {
        if (!is_string($key) || empty($key)) {
            return false;
        }

        $isUpdate = false;
        if (!is_array($data)) {
            $data = explode(',', $data);
        }
        $value = $data;

        $option = self::getOption($key, $alias, $adminId, $expires);
        if ($option) {
            $value = $option;
            if ($field) {
                if (!isset($option[$field])) {
                    $isUpdate = true;
                } elseif (serialize($data) !== serialize($option[$field])) {
                    $isUpdate = true;
                }
                $value[$field] = $data;
            } else {
                if (serialize($data) !== serialize($option)) {
                    $isUpdate = true;
                    $value = $data;
                }
            }
        } else {
            $isUpdate = true;
            if ($field) {
                $value = [$field => $data];
            }
        }

        if ($isUpdate) {
            $where = [
                ['name', '=', $key],
                ['alias', '=', $alias]
            ];
            if ($adminId) {
                $where[] = ['admin_id', '=', $adminId];
            }
            $config = OptionMdl::where($where)->select('id', 'name', 'value')->first();
            if ($config) {
                $result = OptionMdl::where($where)->update([
                    'value' => json_encode($value),
                ]);
            } else {
                $result = OptionMdl::insert([
                    'name' => $key,
                    'alias' => $alias,
                    'admin_id' => $adminId ?: 0,
                    'value' => json_encode($value),
                ]);
            }
            if ($result === false) {
                return false;
            }

            // 缓存
            $cacheKey = 'option--' . $key . '_' . $alias . '_' . $adminId;
            cache([$cacheKey => $value], $expires);
        }

        return true;
    }

    /**
     * 获取配置(通用)
     *
     * @param string $key 配置键值,都小写
     * @return mixed
     */
    public static function getOption($key, $alias, $adminId = '', $expires = 86400)
    {
        if (!is_string($key) || empty($key)) {
            return false;
        }

        $cacheKey = 'option--' . $key . '_' . $alias . '_' . $adminId;
        $option = cache($cacheKey);
        if (empty($option)) {
            $where = [
                ['name', '=', $key],
                ['alias', '=', $alias]
            ];
            if ($adminId) {
                $where[] = ['admin_id', '=', $adminId];
            }
            $config = OptionMdl::where($where)->select('id', 'name', 'value')->first();
            if ($config) {
                $option = $config['value'];
                if ($option) {
                    $option = json_decode($option, true);
                    // 缓存
                    cache([$cacheKey => $option], $expires);
                }
            }
        }

        return $option;
    }
}
